<script setup lang="ts">
import {defineProps, defineEmits, ref, computed} from "vue";
import {ElMessageBox, ElMessage} from "element-plus";
import {createContract, checkContract} from '@/api/contractHomepage/docContractHome';
import {checkNotFamily} from '@/api/familyManagement/docFamily';

const durationYear = ref<number>(1);

const props = defineProps<{
  team: {
    teamId: number,
    teamImg: string,
    teamName: string,
    teamInfo: string,
    signedNumber: number,
    teamPrice: number,
    doctorVoList?: {
      doctorId: number,
      avatar: string,
      doctorName: string,
      department: string
    }[]
  }
}>();

const emits = defineEmits<{
  (e: 'close'): void
}>();

const updatedPrice = computed(() => props.team.teamPrice * durationYear.value);

const handleSign = async () => {
  try {
    // 先检查用户是否已创建家庭
    const familyCheckRes = await checkNotFamily();
    if (familyCheckRes.data === 'CHECK_NOT_FAMILY') {
      ElMessage.warning("请先创建家庭才能预约");
      emits('close'); // 关闭弹窗
      return;
    }
    
    // 再检查签约状态
    const res = await checkContract(props.team.teamId);
    if (res.data === 'CHECK_CONTRACTED') {
      ElMessage.success(`已签约，不可重复提交`);
      return;
    } else if (res.data === 'CHECK_CONTRACTING') {
      ElMessage.warning(`已提交，请勿重复操作`);
      return;
    }

    // 弹出确认框
    await ElMessageBox.confirm(
        `是否确认签约团队 "${props.team.teamName}" ？`,
        '签约确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    );

    // 执行签约
    await createContract({
      userId: 1,
      teamId: props.team.teamId,
      contractDuration: durationYear.value,
    });
    ElMessage.success('提交成功');
    emits('close');

  } catch (err) {
    // 点击取消或者请求出错都关闭弹窗
    emits('close');
  }
};

const handleCancel = () => emits('close');

const increaseDuration = () => {
  if (durationYear.value < 3) durationYear.value++;
};
const decreaseDuration = () => {
  if (durationYear.value > 1) durationYear.value--;
};
</script>

<template>
  <div class="team-detail">
    <!-- 第一盒子 -->
    <div class="top-box">
      <img :src="$urlImage + team.teamImg" alt="团队封面" class="detail-cover"/>
      <div class="basic-info">
        <h2 class="team-name">{{ team.teamName }}</h2>
        <p class="team-info">{{ team.teamInfo }}</p>
        <p class="signed-number">已签约人数：<strong>{{ team.signedNumber }}</strong></p>

        <!-- 签约时长 + 价格（同一行） -->
        <div class="duration-price-row">
          <div class="duration-control">
            <span class="label">签约时长：</span>
            <button class="btn-control" @click="decreaseDuration" :disabled="durationYear <= 1">-</button>
            <span class="duration-text">{{ durationYear }}</span>
            <button class="btn-control" @click="increaseDuration" :disabled="durationYear >= 3">+</button>
            <span class="unit">年</span>
          </div>
          <div class="price-box">
            <span class="price-value">￥{{ updatedPrice }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 第二盒子 -->
    <div class="member-box">
      <h3 class="member-title">团队医生</h3>
      <div v-if="team.doctorVoList?.length" class="doctor-list">
        <div v-for="doctor in team.doctorVoList" :key="doctor.doctorId" class="doctor-card">
          <img :src="$urlImage + doctor.avatar" alt="医生头像" class="doctor-avatar"/>
          <div class="doctor-info">
            <p class="doctor-name">{{ doctor.doctorName }}</p>
            <p class="doctor-dept">{{ doctor.department }}</p>
          </div>
        </div>
      </div>
      <div v-else class="no-doctor">暂无医生</div>
    </div>

    <!-- 第三盒子 -->
    <div class="action-buttons">
      <el-button type="primary" size="medium" @click="handleSign">签约</el-button>
      <el-button type="danger" size="medium" @click="handleCancel">取消</el-button>
    </div>
  </div>
</template>

<style scoped lang="scss">
.team-detail {
  padding: 12px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

/* 第一盒子 */
.top-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;

  .detail-cover {
    width: 100%;
    max-width: 400px; /* 卡片更紧凑 */
    border-radius: 10px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
    object-fit: cover;
  }

  .basic-info {
    margin-top: 8px;

    .team-name {
      font-size: 20px;
      font-weight: bold;
      margin-bottom: 4px;
    }

    .team-info {
      font-size: 13px;
      margin-bottom: 4px;
      color: #555;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      max-width: 100%;
    }

    .signed-number {
      font-size: 13px;
      margin-bottom: 8px;
      color: #555;
    }

    .duration-price-row {
      display: flex;
      justify-content: center;
      align-items: center;
      gap: 20px;
      font-size: 14px;
      margin-top: 12px;

      .duration-control {
        display: flex;
        align-items: center;
        gap: 6px;

        .btn-control {
          width: 26px;
          height: 26px;
          border: 1px solid #ddd;
          border-radius: 4px;
          background: #fff;
          font-size: 15px;
          font-weight: bold;
          cursor: pointer;
          display: flex;
          justify-content: center;
          align-items: center;

          &:hover:not(:disabled) {
            background: #f5f5f5;
          }

          &:disabled {
            opacity: 0.5;
            cursor: not-allowed;
          }
        }

        .duration-text {
          min-width: 20px;
          text-align: center;
          font-weight: bold;
        }

        .unit {
          user-select: none;
        }
      }

      .price-box {
        font-size: 16px;
        font-weight: bold;
        color: #e74c3c;
      }
    }
  }
}

/* 第二盒子 */
.member-box {
  background: #f9f9f9;
  padding: 10px;
  border-radius: 10px;

  .member-title {
    font-size: 15px;
    margin-bottom: 8px;
  }

  .doctor-list {
    display: flex;
    gap: 8px;
    overflow-x: auto;

    &::-webkit-scrollbar {
      height: 5px;
    }

    &::-webkit-scrollbar-thumb {
      background: rgba(0, 0, 0, 0.2);
      border-radius: 3px;
    }
  }

  .doctor-card {
    flex: 0 0 auto;
    display: flex;
    align-items: center;
    width: 150px; /* 卡片小一点 */
    background: #fff;
    border-radius: 8px;
    padding: 6px;
    gap: 8px;

    .doctor-avatar {
      width: 50px;
      height: 50px;
      border-radius: 50%;
      object-fit: cover;
    }

    .doctor-info {
      .doctor-name {
        font-weight: bold;
        font-size: 13px;
      }

      .doctor-dept {
        font-size: 11px;
        color: #777;
      }
    }
  }

  .no-doctor {
    text-align: center;
    color: #888;
    font-size: 13px;
    padding: 8px 0;
  }
}

/* 第三盒子 */
.action-buttons {
  display: flex;
  justify-content: center;
  gap: 14px;
}
</style>
